import React from 'react';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getBase64 } from './upload.util'
import { beforeUploadImage, uploadUrl } from './upload.util'

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
  };

  // 获取父组件传过来的值，这里还可以监听父组件传值变了，然后重新赋值给 state。
  // props 表示父组件传过来的值， state 表示当前子组件的state。
  // static getDerivedStateFromProps(props, state) {
  //   // 父组件传过来的 type 和 子组件的 type 不一样，那么子组件重新赋值。
  //   // 也可以理解成，父组件传过来的值变了。
  //   if (props.fileList.toLocaleString() !== state.fileList.toLocaleString()) {
  //     // 这里执行相应的方法
  //     //把父组件最新的props.type重新赋值到 子组件state.type
  //     return {
  //       fileList: props.fileList
  //     }
  //   }
  //   // 父组件的值没有变化，这里不做任何操作。
  //   return null
  // }

  clear= () => {
    this.setState({
      fileList: []
    })
  };
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ fileList }) => {
    this.setState({ fileList });
    const list = fileList.map(v => v.response ? v.response.data[0] : '').filter(v => !!v);
    this.props.onFileChange && this.props.onFileChange(list);
  };

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传</div>
      </div>
    );
    return (
      <>
        <Upload
          action={uploadUrl}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          accept="image/*"
          beforeUpload={beforeUploadImage}
          onChange={this.handleChange}
        >
          {fileList.length >= 100 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

export default PicturesWall;
